{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Solution:\n",
    "    def searchInsert(self, nums: [int], target: int) -> int:\n",
    "        if len(nums) == 0:\n",
    "            return 0\n",
    "        try:\n",
    "            loc = nums.index(target)\n",
    "        except:\n",
    "            if len(nums) == 1:\n",
    "                if nums[0] > target:\n",
    "                    return 0\n",
    "                else:\n",
    "                    return 1\n",
    "            # divide and conquer\n",
    "            left = 0\n",
    "            right = len(nums) - 1\n",
    "            while left <= right:\n",
    "                mid = (left + right) // 2\n",
    "                if nums[mid] < target:\n",
    "                    left = mid + 1\n",
    "                    loc = mid + 1\n",
    "                else:\n",
    "                    right = mid - 1\n",
    "                    loc = mid\n",
    "        return loc"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2\n"
     ]
    }
   ],
   "source": [
    "s = Solution()\n",
    "print(s.searchInsert([1,3,5,6], 4))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "py3",
   "language": "python",
   "name": "py3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
